package com.qf.fmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.fmall.product.entity.ProductComments;
import com.qf.fmall.product.mapper.ProductCommentsDao;
import com.qf.fmall.product.service.IProductCommentsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.fmall.user.entity.User;
import com.qf.fmall.user.mapper.UserDao;
import com.qf.fmall.vo.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dongjl
 * @since 2024-01-17
 */
@Service
public class ProductCommentsServiceImpl extends ServiceImpl<ProductCommentsDao, ProductComments> implements IProductCommentsService {

    @Autowired
    private UserDao userDao;


    @Override
    public PageVo detailCommonts(Integer id, Integer pageNum, Integer limit) {

        //1. 创建分页对象
        Page<ProductComments> page = new Page<>(pageNum, limit);

        //2. 创建查询条件对象
        QueryWrapper<ProductComments> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id",id);

        page(page,queryWrapper);
        List<ProductComments> records = page.getRecords();
        // 添加缺少的用户信息
        addUserData(records);

        //3. 获取分页信息
        PageVo pageVo = new PageVo();
        pageVo.setCount(page.getTotal());
        pageVo.setPageCount(page.getPages());
        pageVo.setList(records);
        return pageVo;
    }


    private void addUserData(List<ProductComments> records) {
        for (ProductComments record : records) {
            String userId = record.getUserId();
            User user = userDao.selectById(userId);
            record.setUsername(user.getUsername());
            record.setNickname(user.getNickname());
            record.setUserImg(user.getUserImg());
        }
    }
}
